package com.flyco.modules.sms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.flyco.modules.pms.entity.PmsProduct;
import com.flyco.modules.pms.entity.PmsProductCategory;
import com.flyco.modules.pms.service.IPmsProductCategoryService;
import com.flyco.modules.pms.service.IPmsProductService;
import com.flyco.modules.sms.entity.*;
import com.flyco.modules.sms.mapper.SmsGiftInfoMapper;
import com.flyco.modules.sms.model.SmsGiftExistModel;
import com.flyco.modules.sms.model.SmsGiftInfoModel;
import com.flyco.modules.sms.service.*;
import com.flyco.modules.stm.entity.StmDistributorGroup;
import com.flyco.modules.stm.entity.StmStoreInfo;
import com.flyco.modules.stm.service.IStmDistributorGroupService;
import com.flyco.modules.stm.service.IStmStoreInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 赠品配置表
 * @Author: flyco
 * @Date: 2023-02-03
 * @Version: V1.0
 */
@Service
public class SmsGiftInfoServiceImpl extends ServiceImpl<SmsGiftInfoMapper, SmsGiftInfo> implements ISmsGiftInfoService {
    @Autowired
    private ISmsGiftProductCategoryRelationService smsGiftProductCategoryRelationService;
    @Autowired
    private ISmsGiftProductRelationService smsGiftProductRelationService;
    @Autowired
    private IPmsProductService pmsProductService;
    @Autowired
    private IPmsProductCategoryService pmsProductCategoryService;
    @Autowired
    private ISmsGiftStoreRelationService giftStoreRelationService;
    @Autowired
    private ISmsGiftStoreGroupRelationService smsGiftStoreGroupRelationService;
    @Autowired
    private IStmDistributorGroupService distributorGroupService;
    @Autowired
    private IStmStoreInfoService stmStoreInfoService;
    @Autowired
    private SmsGiftInfoMapper giftInfoMapper;

    @Override
    public String checkRelation(SmsGiftInfoModel smsGiftInfoModel) {
        if (smsGiftInfoModel.getUseType() == 1) {
            //如果是指定分类，分类id必传
            if (smsGiftInfoModel.getCategoryList() == null || smsGiftInfoModel.getCategoryList().size() == 0) {
                return "分类id必传";
            }
        }

        if (smsGiftInfoModel.getUseType() == 2) {
            //如果是指定商品，商品id必传
            if (smsGiftInfoModel.getProductList() == null || smsGiftInfoModel.getProductList().size() == 0) {
                return "商品id必传";
            }
        }

        if (smsGiftInfoModel.getStoreType() == 1) {
            //如果是指定分组，分组id必传
            if (smsGiftInfoModel.getStoreGroupList() == null || smsGiftInfoModel.getStoreGroupList().size() == 0) {
                return "分组id必传";
            }
        }

        if (smsGiftInfoModel.getStoreType() == 2) {
            //如果是指定商品，商品id必传
            if (smsGiftInfoModel.getStoreList() == null || smsGiftInfoModel.getStoreList().size() == 0) {
                return "经销商id必传";
            }
        }

        //查询有效的其他活动
        Date now = new Date();
        List<SmsGiftInfo> list;
        //如果是编辑，就排除编辑的那个活动id
        if (smsGiftInfoModel.getId() != null) {
            list = this.list(Wrappers.lambdaQuery(SmsGiftInfo.class).eq(SmsGiftInfo::getPartnerId, 0L).eq(SmsGiftInfo::getCancelFlag, 0).eq(SmsGiftInfo::getStatus, 1)
                    .eq(SmsGiftInfo::getBrandCategory, smsGiftInfoModel.getBrandCategory())
                    // .le(SmsGiftInfo::getStartTime, now).gt(SmsGiftInfo::getEndTime, now).ne(SmsGiftInfo::getId, smsGiftInfoModel.getId()));
                    .and(q -> q.ge(SmsGiftInfo::getStartTime, smsGiftInfoModel.getStartTime()).lt(SmsGiftInfo::getStartTime, smsGiftInfoModel.getEndTime())
                            .or().le(SmsGiftInfo::getStartTime, smsGiftInfoModel.getStartTime()).gt(SmsGiftInfo::getEndTime, smsGiftInfoModel.getEndTime())
                            .or().gt(SmsGiftInfo::getEndTime, smsGiftInfoModel.getStartTime()).le(SmsGiftInfo::getEndTime, smsGiftInfoModel.getEndTime())
                    )
            );
        } else {
            list = this.list(Wrappers.lambdaQuery(SmsGiftInfo.class).eq(SmsGiftInfo::getPartnerId, 0L).eq(SmsGiftInfo::getCancelFlag, 0).eq(SmsGiftInfo::getStatus, 1)
                    .eq(SmsGiftInfo::getBrandCategory, smsGiftInfoModel.getBrandCategory())
                    // .lt(SmsGiftInfo::getStartTime, smsGiftInfoModel.getStartTime()).gt(SmsGiftInfo::getEndTime, smsGiftInfoModel.getStartTime())
                    .and(q -> q.ge(SmsGiftInfo::getStartTime, smsGiftInfoModel.getStartTime()).lt(SmsGiftInfo::getStartTime, smsGiftInfoModel.getEndTime())
                            .or().le(SmsGiftInfo::getStartTime, smsGiftInfoModel.getStartTime()).gt(SmsGiftInfo::getEndTime, smsGiftInfoModel.getEndTime())
                            .or().gt(SmsGiftInfo::getEndTime, smsGiftInfoModel.getStartTime()).le(SmsGiftInfo::getEndTime, smsGiftInfoModel.getEndTime())
                    )
            );
        }

        if (list.isEmpty()) {
            //没有配置活动，直接返回
            return null;
        }
        if (list.stream().anyMatch(q -> q.getUseType() == 0)) {
            return "存在全场通用的活动，本次不允许配置";
        }

        //如果本次配置的是全场通用，那么不能有其他活动(list不为空不行)
        if (smsGiftInfoModel.getUseType() == 0) {
            return "配置全场通用的活动时，不允许存在其他有效的活动";
        }
        //如果本次配置的是指定分类，要查询其他活动：包括指定分类和指定商品（查询这些商品的分类），校验分类不能重复配置
        else if (smsGiftInfoModel.getUseType() == 1) {
            //1.根据活动，查询分类数据
            List<Long> categoryIds = getCategoryIds(list);

            //2.根据活动，查询这些商品所属的分类
            List<Long> productIds = getProductIds(list);
            if (!productIds.isEmpty()) {
                //查询这些商品的分类
                List<Long> collect = pmsProductService.list(Wrappers.lambdaQuery(PmsProduct.class)
                        .select(PmsProduct::getProductCategoryId)
                        .in(PmsProduct::getId, productIds))
                        .stream().map(PmsProduct::getProductCategoryId).distinct().collect(Collectors.toList());
                categoryIds.addAll(collect);
            }

            //比较已配置的分类和本次的分类是否有重复
            for (Long categoryId : smsGiftInfoModel.getCategoryList()) {
                if (categoryIds.contains(categoryId)) {
                    return "商品的分类信息不能重复";
                }
            }
            //如果本次配置的是指定商品，就查询其他活动有没有相同的商品，商品不能重复配置
        } else if (smsGiftInfoModel.getUseType() == 2) {
            //1.根据活动的指定商品，查询这些商品
            List<Long> productIds = getProductIds(list);
            //2.根据活动的指定分类，查询这些分类下的所有商品
            List<Long> categoryIds = getCategoryIds(list);
            if (!categoryIds.isEmpty()) {
                //根据分类，查询商品
                List<Long> collect = pmsProductService.list(Wrappers.lambdaQuery(PmsProduct.class)
                        .select(PmsProduct::getId)
                        .in(PmsProduct::getProductCategoryId, categoryIds))
                        .stream().map(PmsProduct::getId).collect(Collectors.toList());
                productIds.addAll(collect);
            }

            //比较已配置的商品和本次的商品是否有重复
            for (Long productId : smsGiftInfoModel.getProductList()) {
                if (productIds.contains(productId)) {
                    return "商品信息不能重复";
                }
            }
        }

        return null;
    }


    @Override
    public String checkRelation2(SmsGiftInfoModel smsGiftInfoModel) {
        if (smsGiftInfoModel.getUseType() == 1) {
            //如果是指定分类，分类id必传
            if (smsGiftInfoModel.getCategoryList() == null || smsGiftInfoModel.getCategoryList().size() == 0) {
                return "分类id必传";
            }
        }

        if (smsGiftInfoModel.getUseType() == 2) {
            //如果是指定商品，商品id必传
            if (smsGiftInfoModel.getProductList() == null || smsGiftInfoModel.getProductList().size() == 0) {
                return "商品id必传";
            }
        }

        if (smsGiftInfoModel.getStoreType() == 1) {
            //如果是指定分组，分组id必传
            if (smsGiftInfoModel.getStoreGroupList() == null || smsGiftInfoModel.getStoreGroupList().size() == 0) {
                return "分组id必传";
            }
        }

        if (smsGiftInfoModel.getStoreType() == 2) {
            //如果是指定商品，商品id必传
            if (smsGiftInfoModel.getStoreList() == null || smsGiftInfoModel.getStoreList().size() == 0) {
                return "经销商id必传";
            }
        }

        //先查询是否有在要创建的时间范围内有通用活动存在，有的话直接返回。
        List<SmsGiftInfo> list = this.list(Wrappers.lambdaQuery(SmsGiftInfo.class)
                .eq(SmsGiftInfo::getPartnerId, 0L)
                .eq(SmsGiftInfo::getCancelFlag, 0)
                .eq(SmsGiftInfo::getStatus, 1)
                .eq(SmsGiftInfo::getBrandCategory, smsGiftInfoModel.getBrandCategory())
                .eq(SmsGiftInfo::getUseType, 0)
                .eq(SmsGiftInfo::getStoreType, 0)
                .and(q -> q.ge(SmsGiftInfo::getStartTime, smsGiftInfoModel.getStartTime()).lt(SmsGiftInfo::getStartTime, smsGiftInfoModel.getEndTime())
                        .or().le(SmsGiftInfo::getStartTime, smsGiftInfoModel.getStartTime()).gt(SmsGiftInfo::getEndTime, smsGiftInfoModel.getEndTime())
                        .or().gt(SmsGiftInfo::getEndTime, smsGiftInfoModel.getStartTime()).le(SmsGiftInfo::getEndTime, smsGiftInfoModel.getEndTime())
                )
        );
        if (smsGiftInfoModel.getId() != null && CollectionUtil.isNotEmpty(list)) {
            if (list.stream().filter(o -> !o.getId().equals(smsGiftInfoModel.getId())).count() > 0) {
                return "存在全场通用的活动，本次不允许配置";
            }
        } else if (smsGiftInfoModel.getId() == null && CollectionUtil.isNotEmpty(list)) {
            return "存在全场通用的活动，本次不允许配置";
        }


        //如果传的商品，把商品的类别提取出来，放到类别中来查询，看是否有相同的类别存在，同时也查询是否有相同的商品存在


        List<SmsGiftExistModel> giftList = giftInfoMapper.queryGift(smsGiftInfoModel);
        if (smsGiftInfoModel.getId() == null && CollectionUtil.isNotEmpty(giftList)) {
            return "已存在其他有效的活动，本次不允许配置";
        } else if (smsGiftInfoModel.getId() != null && CollectionUtil.isNotEmpty(giftList)) {
            if (giftList.stream().filter(o -> !o.getGiftId().equals(smsGiftInfoModel.getId())).count() > 0) {
                return "已存在其他有效的活动，本次不允许配置";
            }
        }
        return null;
    }

    private List<Long> getCategoryIds(List<SmsGiftInfo> list) {
        List<SmsGiftInfo> giftCategoryList = list.stream().filter(q -> q.getUseType() == 1).collect(Collectors.toList());
        if (giftCategoryList.isEmpty()) {
            return new ArrayList<>();
        }
        return smsGiftProductCategoryRelationService.list(Wrappers.lambdaQuery(SmsGiftProductCategoryRelation.class)
                .select(SmsGiftProductCategoryRelation::getProductCategoryId)
                .in(SmsGiftProductCategoryRelation::getGiftId, giftCategoryList.stream().map(SmsGiftInfo::getId).collect(Collectors.toList())))
                .stream().map(SmsGiftProductCategoryRelation::getProductCategoryId).collect(Collectors.toList());
    }

    private List<Long> getProductIds(List<SmsGiftInfo> list) {
        List<SmsGiftInfo> giftProductList = list.stream().filter(q -> q.getUseType() == 2).collect(Collectors.toList());
        if (giftProductList.isEmpty()) {
            return new ArrayList<>();
        }

        //查询已配置的商品
        return smsGiftProductRelationService.list(Wrappers.lambdaQuery(SmsGiftProductRelation.class)
                .select(SmsGiftProductRelation::getProductId)
                .in(SmsGiftProductRelation::getGiftId, giftProductList.stream().map(SmsGiftInfo::getId).collect(Collectors.toList())))
                .stream().map(SmsGiftProductRelation::getProductId).collect(Collectors.toList());
    }

    @Override
    public void addRelation(Long giftId, SmsGiftInfoModel smsGiftInfoModel) {
        //如果是编辑，先删除原来的数据
        if (smsGiftInfoModel.getId() != null) {
            smsGiftProductCategoryRelationService.remove(Wrappers.lambdaQuery(SmsGiftProductCategoryRelation.class).in(SmsGiftProductCategoryRelation::getGiftId, giftId));
            smsGiftProductRelationService.remove(Wrappers.lambdaQuery(SmsGiftProductRelation.class).in(SmsGiftProductRelation::getGiftId, giftId));
            giftStoreRelationService.remove(Wrappers.lambdaQuery(SmsGiftStoreRelation.class).in(SmsGiftStoreRelation::getGiftId, giftId));
            smsGiftStoreGroupRelationService.remove(Wrappers.lambdaQuery(SmsGiftStoreGroupRelation.class).in(SmsGiftStoreGroupRelation::getGiftId, giftId));
        }

        //添加经销商分组或添加指定经销商
        addStoreRelation(giftId, smsGiftInfoModel);
        //添加产品分类或指定产品分类
        addProductRelation(giftId, smsGiftInfoModel);
    }

    private void addStoreRelation(Long giftId, SmsGiftInfoModel smsGiftInfoModel) {

        SmsGiftInfo giftInfo = giftInfoMapper.selectById(giftId);

        //指定分组
        if (smsGiftInfoModel.getStoreType() == 1) {
            //根据分组id查询分组信息
            List<StmDistributorGroup> list = distributorGroupService.list(Wrappers.lambdaQuery(StmDistributorGroup.class).in(StmDistributorGroup::getId, smsGiftInfoModel.getStoreGroupList()));
            List<SmsGiftStoreGroupRelation> collect = list.stream().map(one -> {
                SmsGiftStoreGroupRelation storeGroupRelation = new SmsGiftStoreGroupRelation();
                storeGroupRelation.setGiftId(giftId);
                storeGroupRelation.setStoreGroupId(one.getId());
                storeGroupRelation.setStoreGroupName(one.getName());
                return storeGroupRelation;
            }).collect(Collectors.toList());
            smsGiftStoreGroupRelationService.saveBatch(collect);
            //把指定分组的经销商也插入了经销商表中，方便后面查询活动唯一性
            giftStoreRelationService.insertStoreRelationForGroupId(smsGiftInfoModel.getStoreGroupList(), giftId,giftInfo.getBrandCategory());
        }
        //指定经销商
        else if (smsGiftInfoModel.getStoreType() == 2) {
            //根据商品id查询商品信息
            List<StmStoreInfo> list = stmStoreInfoService.list(Wrappers.lambdaQuery(StmStoreInfo.class).in(StmStoreInfo::getStoreId, smsGiftInfoModel.getStoreList()));
            List<SmsGiftStoreRelation> collect = list.stream().map(one -> {
                SmsGiftStoreRelation giftStoreRelation = new SmsGiftStoreRelation();
                giftStoreRelation.setGiftId(giftId);
                giftStoreRelation.setStoreId(one.getStoreId());
                giftStoreRelation.setStoreName(one.getName());
                giftStoreRelation.setStoreGroupId(one.getGroupId() == null ? 0 : one.getGroupId());
                return giftStoreRelation;
            }).collect(Collectors.toList());
            giftStoreRelationService.saveBatch(collect);
        }

    }

    private void addProductRelation(Long giftId, SmsGiftInfoModel smsGiftInfoModel) {

        //指定分类
        if (smsGiftInfoModel.getUseType() == 1) {
            //根据分类id查询分类信息
            List<PmsProductCategory> list = pmsProductCategoryService.list(Wrappers.lambdaQuery(PmsProductCategory.class).in(PmsProductCategory::getId, smsGiftInfoModel.getCategoryList()));
            List<SmsGiftProductCategoryRelation> collect = list.stream().map(one -> {
                SmsGiftProductCategoryRelation categoryRelation = new SmsGiftProductCategoryRelation();
                categoryRelation.setGiftId(giftId);
                categoryRelation.setProductCategoryId(one.getId());
                categoryRelation.setProductCategoryName(one.getName());
                return categoryRelation;
            }).collect(Collectors.toList());
            smsGiftProductCategoryRelationService.saveBatch(collect);

            //把分类下的产品也插入产品关系表中，方便后面查询。
            smsGiftProductRelationService.insertProductRelationForCategoryId(smsGiftInfoModel.getCategoryList(), giftId);

        }
        //指定商品
        else if (smsGiftInfoModel.getUseType() == 2) {
            //根据商品id查询商品信息
            List<PmsProduct> list = pmsProductService.list(Wrappers.lambdaQuery(PmsProduct.class).in(PmsProduct::getId, smsGiftInfoModel.getProductList()));
            List<SmsGiftProductRelation> collect = list.stream().map(one -> {
                SmsGiftProductRelation productRelation = new SmsGiftProductRelation();
                productRelation.setGiftId(giftId);
                productRelation.setProductId(one.getId());
                productRelation.setProductName(one.getName());
                productRelation.setProductSn(one.getProductSn());
                productRelation.setProductCategoryId(one.getProductCategoryId());
                return productRelation;
            }).collect(Collectors.toList());
            smsGiftProductRelationService.saveBatch(collect);
        }
    }

    @Override
    public void removeRelation(Long giftId) {
        smsGiftProductCategoryRelationService.remove(Wrappers.lambdaQuery(SmsGiftProductCategoryRelation.class).in(SmsGiftProductCategoryRelation::getGiftId, giftId));
        smsGiftProductRelationService.remove(Wrappers.lambdaQuery(SmsGiftProductRelation.class).in(SmsGiftProductRelation::getGiftId, giftId));
        giftStoreRelationService.remove(Wrappers.lambdaQuery(SmsGiftStoreRelation.class).in(SmsGiftStoreRelation::getGiftId, giftId));
        smsGiftStoreGroupRelationService.remove(Wrappers.lambdaQuery(SmsGiftStoreGroupRelation.class).in(SmsGiftStoreGroupRelation::getGiftId, giftId));
    }

    @Override
    public List<SmsGiftProductRelation> queryProductyRelationById(Long id) {
        LambdaQueryWrapper<SmsGiftProductRelation> categoryQuery = new LambdaQueryWrapper<>();
        categoryQuery.eq(SmsGiftProductRelation::getGiftId, id);
        return smsGiftProductRelationService.list(categoryQuery);
    }

    @Override
    public List<SmsGiftProductCategoryRelation> queryCategoryRelationById(Long id) {
        LambdaQueryWrapper<SmsGiftProductCategoryRelation> categoryQuery = new LambdaQueryWrapper<>();
        categoryQuery.eq(SmsGiftProductCategoryRelation::getGiftId, id);
        return smsGiftProductCategoryRelationService.list(categoryQuery);
    }

    @Override
    public List<SmsGiftStoreRelation> queryStoreRelationById(Long id) {
        LambdaQueryWrapper<SmsGiftStoreRelation> storeQuery = new LambdaQueryWrapper<>();
        storeQuery.eq(SmsGiftStoreRelation::getGiftId, id);
        return giftStoreRelationService.list(storeQuery);
    }

    @Override
    public List<SmsGiftStoreGroupRelation> queryStoreGroupRelationById(Long id) {
        LambdaQueryWrapper<SmsGiftStoreGroupRelation> storeGroupQuery = new LambdaQueryWrapper<>();
        storeGroupQuery.eq(SmsGiftStoreGroupRelation::getGiftId, id);
        return smsGiftStoreGroupRelationService.list(storeGroupQuery);
    }
}
